package com.dianrui.agent.activity;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.dianrui.agent.R;
import com.dianrui.agent.bean.FixedBean;
import com.dianrui.agent.util.JsonUtils;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TrackPathActivity extends BaseActivity {
    private String mOrderId,mstartTimes,mendTimes;
    private AMap aMap;
    private List<LatLng> gps = new ArrayList<>();
    private List<LatLng> marea_points = new ArrayList<>();


    @BindView(R.id.mapviews)
    MapView mapviews;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.start_times)
    TextView startTimes;
    @BindView(R.id.end_times)
    TextView endTimes;

    @BindView(R.id.bottom_text)
    TextView bottomTV;

    private int tagFrom;
    public static int TAG_FROM_PROGRESS=1;//进行中
    public static int TAG_FROM_UNPAY=2;//未付款

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapviews.onCreate(savedInstanceState);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activty_trackpath;
    }

    @Override
    public void initView() {
      title.setText("订单详情");
        if (getIntent() != null && getIntent().getExtras()!=null) {
            Bundle bundle=getIntent().getExtras();
            if (bundle != null) {
                mOrderId=bundle.getString("orderid");
                mstartTimes=bundle.getString("starttime");
                mendTimes=bundle.getString("endtime");
                tagFrom=bundle.getInt("tagFrom");
            }
            startTimes.setText(mstartTimes);
            endTimes.setText(mendTimes);

        }
        //进行中
        if (tagFrom == TAG_FROM_PROGRESS) {
            bottomTV.setVisibility(View.VISIBLE);
            bottomTV.setText("远程还车");
        }else if(tagFrom==TAG_FROM_UNPAY){
            bottomTV.setVisibility(View.VISIBLE);
            bottomTV.setText("确认付款");
        }
        if (aMap == null) {
            aMap = mapviews.getMap();
        }
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setZoomControlsEnabled(false);
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                getOrderDetails();
                getArea();
            }
        });
    }

    private void getOrderDetails() {
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("order_id",mOrderId);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl()+Url.ORDERTAILS,jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("gps");
                            String fixed_list= JsonUtils.getJsonStr(JsonUtils.getJsonStr(result,"data"),"fixed_list");
                            if(fixed_list!=null&&fixed_list.length()>2){
                                List<FixedBean> fixedlist=JsonUtils.jsonStrToList(fixed_list,new TypeToken<List<FixedBean>>(){}.getType());
                                if (fixedlist != null && !fixedlist.isEmpty()) {

                                    //TODO 画区域

                                    for(int i=0;i<fixedlist.size();i++){

                                        List<LatLng> points = new ArrayList<>();
                                        if(fixedlist.get(i).fixed_path==null||fixedlist.get(i).fixed_path.isEmpty()){
                                            continue;
                                        }
                                        for(int j=0;j<fixedlist.get(i).fixed_path.size();j++){
                                            points.add(new LatLng(fixedlist.get(i).fixed_path.get(j).lat,fixedlist.get(i).fixed_path.get(j).lng));
                                        }
                                        points.add(new LatLng(fixedlist.get(i).fixed_path.get(0).lat,fixedlist.get(i).fixed_path.get(0).lng));

                                        aMap.addPolygon(new PolygonOptions()
                                                .addAll(points).strokeWidth(4)
                                                .fillColor(getResources().getColor(R.color.gray_transparent)));

                                        List<BitmapDescriptor> textureList = new ArrayList<>();
                                        textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.customer_img));

                                        List<Integer> textureIndexs = new ArrayList<>();
                                        textureIndexs.add(i);
                                        aMap.addPolyline(new PolylineOptions()
                                                .addAll(points).width(4)
                                                .setCustomTextureList(textureList)
                                                .setCustomTextureIndex(textureIndexs).setDottedLine(true));

                                    }

                                }

                            }
                            if (jsonArray.length() > 0) {
                                LatLng current = new LatLng(jsonArray.optJSONObject(0).optDouble("lat"), jsonArray.optJSONObject(0).getDouble("lng"));
                                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(current, 14));
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    gps.add(new LatLng(jsonArray.optJSONObject(i).optDouble("lat"), jsonArray.optJSONObject(i).getDouble("lng")));
                                }

                                View startPointView = LayoutInflater.from(TrackPathActivity.this).inflate(R.layout.start_point, null);


                                Marker marker = aMap.addMarker(new MarkerOptions().position(new LatLng(jsonArray.optJSONObject(0).optDouble("lat"), jsonArray.optJSONObject(0).optDouble("lng"))).icon(BitmapDescriptorFactory.fromView(startPointView)).zIndex(99));

                                View endPointView = LayoutInflater.from(TrackPathActivity.this).inflate(R.layout.end_point, null);

                                Marker marker1= aMap.addMarker(new MarkerOptions().position(new LatLng(jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("lat"), jsonArray.optJSONObject(jsonArray.length() - 1).getDouble("lng"))).icon(BitmapDescriptorFactory.fromView(endPointView)).zIndex(100));


                                if (gps.size() > 1) {
                                    List<BitmapDescriptor> textureList = new ArrayList<>();
                                    textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.arrow_texture1));

                                    List<Integer> textureIndexs = new ArrayList<>();
                                    textureIndexs.add(0);
                                    aMap.addPolyline(new PolylineOptions().
                                            addAll(gps).width(4).setCustomTextureList(textureList).setCustomTextureIndex(textureIndexs).setDottedLine(true));
                                }
                            }
                        }else {
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    private void getArea() {
        if (!StringUtils.isEmpty(spUtils.getString("area"))) {
            try {
                final JSONObject jsonObject = new JSONObject(spUtils.getString("area"));
                if (jsonObject != null) {
                    if (marea_points != null) {
                        marea_points.clear();
                    }
                    JSONArray gfixed_path = jsonObject.optJSONObject("data").optJSONArray("fixed_path");
                    if (gfixed_path.length() > 0) {
                        for (int j = 0; j < gfixed_path.length(); j++) {
                            JSONObject jsonObject3 = gfixed_path.optJSONObject(j);
                            marea_points.add(new LatLng(jsonObject3.optDouble("lat"), jsonObject3.optDouble("lng")));
                        }

                        if (marea_points.size() > 0) {
                            PolygonOptions polygonOptions = new PolygonOptions();
                            polygonOptions.addAll(marea_points);
                            polygonOptions.strokeWidth(6);
                            polygonOptions.strokeColor(Color.rgb(255, 0, 0));
                            polygonOptions.fillColor(Color.argb(0, 255, 0, 0));
                            aMap.addPolygon(polygonOptions);
                        }
                    }

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mapviews.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapviews.onPause();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapviews.onSaveInstanceState(outState);
    }



    @OnClick({R.id.back,R.id.bottom_text})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.back:
                finish();
                break;

            case R.id.bottom_text:
                //进行中
                if (tagFrom == TAG_FROM_PROGRESS) {
                    remoteCars(mOrderId);
                }else if(tagFrom==TAG_FROM_UNPAY){
//                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                    builder.setMessage("确认付款后用户无需支付车费，是否需要确认？");
//                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                        }
//                    });
//                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                        }
//                    });
//                    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
//
//                        @Override
//                        public void onCancel(DialogInterface dialog) {
//                            dialog.dismiss();
//                        }
//                    });
//                    builder.show();
                    payments(mOrderId);
                }

                break;
            default:

                break;
        }

    }

    /**
     * 远程还车
     * @param orderId
     */
    private void remoteCars(String orderId) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("order_id", orderId);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl() + Url.REMOTELOCK, jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }



    /**
     * 确认付款
     * @param orderId
     */
    private ProgressDialog mProgressDialog;
    private void payments(String orderId) {
        mProgressDialog=new ProgressDialog(this);
        mProgressDialog.setMessage("正在帮你付款,请稍候...");
        mProgressDialog.show();
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("order_id",orderId);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl()+Url.CONFIRMLOCK, jsonObject.toString(),  new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            mProgressDialog.dismiss();
                            ToastUtil.showToast(jsonObject.optString("message"));
                            setResult(RESULT_OK);
                            finish();
                        }else {
                            mProgressDialog.dismiss();
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                mProgressDialog.dismiss();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapviews.onDestroy();
        if (gps != null) {
            gps.clear();
        }
        if (marea_points != null) {
            marea_points.clear();
        }
    }
}
